package org.example.demo2.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @ClassName RabbitManager
 * @Description 封装消息并发送
 * @Author Kx
 * @Date 2025/10/15 11:05
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
public class RabbitManager<T> {
    private final RabbitTemplate rabbitTemplate;

    /**
     * @author: kx
     * @date: 2025/10/15 11:06
     * @param exchange : 交换机
     * @param routingKey : 路由键
     * @param callbackBeanName : 回调方法名
     * @param data : 发送的数据
     * @description: 投递消息
    */
    public void send(String exchange, String routingKey, String callbackBeanName, T data) {
        try {
            // 创建 cdata 对象并设置一个 id
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());

            // 将投递的数据转换为 byte[] 类型
            byte[] bytes = new ObjectMapper().writeValueAsBytes(data);
            // 将 bytes 封装为 message 对象
            Message message = new Message(bytes);
            // 创建一个投递失败时返回的消息对象
            ReturnedMessage returnedMessage = new ReturnedMessage(message, 0, callbackBeanName, exchange, routingKey);
            // 将 ReturnedMessage 保存到 correlationData 中
            correlationData.setReturned(returnedMessage);
            // 投递消息
            rabbitTemplate.convertAndSend(exchange, routingKey, data, correlationData);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
